﻿using BaseAuthRole.AspNetCore;
using BaseAuthRole.Domain.Input;
using BaseAuthRole.DTO.Auth;
using BaseAuthRole.IService;
using BaseAuthRole.Service;
using BaseAuthRole.Web.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Tool.Base;
using System.Data;
using System.Drawing.Printing;
using System.Xml.Linq;

namespace BaseAuthRole.Web.Api.Client
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AppForClientController : ControllerBase
    {

        private IApplicationService _applictationService;
        private IUserService _userService;
        public AppForClientController(IApplicationService applictationService, IUserService userService)
        {
            this._applictationService = applictationService;
            this._userService = userService;
        }

        /// <summary>
        /// 添加/编辑app
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddApp([FromBody] AddAppInput input)
        {            
            var result = new CommonResult();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput {Uid = input.Uid, Id = "", AppId = "", AppAccessToken = ""}).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("AppManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            result.IsError = true;
            if (string.IsNullOrEmpty(input.AppId))
            {
                var app = new ApplicationModel
                {
                    Secret = SecretHelper.GetMD5(Guid.NewGuid().ToString("N")),
                    Name = input.Name,
                    Description = input.Description,
                    AuthDomain = input.AuthDomain
                };

                var r = this._applictationService.AddApplication(app);

                if (r > 0)
                {
                    result.IsError = false;
                    result.Result = app.Id;
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                }
                else
                {
                    result.Message = "操作失败";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                }
            }
            else
            {
                var app = this._applictationService.GetApplicationModel(input.AppId);

                if (app == null)
                {
                    result.Message = "无效的appid";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.DisabledApp;
                    return Ok(result);
                }
                else
                {
                    app.Name = input.Name;
                    app.Description = input.Description;
                    app.AuthDomain = input.AuthDomain;

                    var r = this._applictationService.UpdateApplicationModel(app);
                    if (r > 0)
                    {
                        result.IsError = false;
                        result.Result = app.Id;
                        result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                    }
                    else
                    {
                        result.Message = "操作失败";
                        result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                    }
                }
            }
            return Ok(result);
        }

        /// <summary>
        /// 获取app列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetApp([FromQuery] GetAppInput input)
        {

            var result = new CommonResult<PageModel<ApplicationModel>>();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput {Uid = input.Uid, Id = "", AppId = "", AppAccessToken = ""}).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("AppManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            var condition = "";
            long count = 0;
            var paraObj = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(input.Name))
            {
                condition += " \"Name\" like @para";
                paraObj.Add("para", $"%{input.Name}%");
            }
            var info = this._applictationService.GetApplicationModel(input.Page, input.PageSize, condition, " \"CreateTime\" desc", out count, paraObj);
            result.IsError = false;
            result.Result = new PageModel<ApplicationModel>()
            {
                Data = info.ToList(),
                DataCount = count,
                Page = input.Page,
                PageCount = Convert.ToInt32(Math.Ceiling(count / (decimal)input.PageSize)),
                PageSize = input.PageSize
            };

            return Ok(result);
        }

        /// <summary>
        /// 禁用/启用
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult EditAppStatus([FromBody] EditAppStatusInput input)
        {
            var result = new CommonResult();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput {Uid = input.Uid, Id = "", AppId = "", AppAccessToken = ""}).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("AppManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            var app = this._applictationService.GetApplicationModel(input.AppId);
            if (app == null)
            {
                result.Message = "无效的appid";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.DisabledApp;
                return Ok(result);
            }
            app.Status = input.Status;
            this._applictationService.UpdateApplicationModel(app);
            result.IsError = false;
            return Ok(result);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult DelApp([FromQuery] DelAppInput input)
        {
            var result = new CommonResult();

            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput {Uid = input.Uid, Id = "", AppId = "", AppAccessToken = ""}).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.Contains("AppManage")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            int r = this._applictationService.DeleteApplicationModel(input.AppId);
            if (r <= 0)
            {
                result.Message = "删除失败";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }
            result.IsError = false;
            result.Message = "删除成功";
            return Ok(result);
        }
    }
}
